from datetime import datetime
from apps.common.utils.response import response_message, response_success, response_action
from decimal import Decimal
import random
import json
from apps.common.utils.tools import random_num

from apps.pay.order.dao import OrderDao
from apps.system.rank.dao import RankDao
from apps.merchant.sku.dao import SkuDao
from apps.merchant.item.dao import ItemDao
from apps.merchant.sku.dao import SkuDao
from apps.user.dao import UserDao

from apps.pay.order.payReturnHandle.upRank import upRankHandle
from apps.pay.order.payReturnHandle.buyItem import buyItemHandle
from apps.common.ali.sendSms.service import sendSmsForAli
from apps.chat.message.service import sendMessage
from apps.pay.order.payReturnHandle.goldCustomActivity import goldCustomHandle
from apps.user.countVerticalData import updateVerticalPerformance
from apps.user.countTeamDate import updateTeamPerformance


# 设置实际支付价格
def setPayMoney(params, data, user):
    print('设置实际支付金额', data.get('scene'), params.get('orderItemList'))
    if data.get('scene') == 'generay' or data.get('scene') == 'goldCustom':
        realPay = 0
        for orderItem in params.get('orderItemList'):
            if orderItem.get('sku'):
                sku = SkuDao().findOneByObjId(orderItem.get('sku'))
                realPay = realPay + sku.sellingPrice * orderItem.get('payCount')
        return realPay.quantize(Decimal("0.00"))
    elif data.get('scene') == 'guest':
        realPay = 0
        for orderItem in params.get('orderItemList'):
            if orderItem.get('item'):
                sku = UserDao().findOneByObjId(orderItem.get('item'))
                realPay = realPay + sku.sellingPrice * orderItem.get('payCount')
        return realPay.quantize(Decimal("0.00"))
    else:
        print('支付场景不存在')
        return 0
    
# 随机立减
def random_sub(money, m, n):
    _random = random.uniform(m, n)
    if money > Decimal(_random):
        money = money - Decimal(_random)
    return money.quantize(Decimal("0.00"))

# 创建订单之前校验
def beforeCreateOrderScene(params, data, user):
    print('创建订单之前校验', params)
    if data.get('scene') == 'generay' or data.get('scene') == 'goldCustom':
        # print('校验库存', params.get('orderItemList'))
        orderItemList = params.get('orderItemList')
        for orderItem in orderItemList:
            # 检验是否上架
            item = ItemDao().findOneByObjId(orderItem.get('item'))
            if item.status == 0:
                return response_message('商品'+ item.name +'暂未上架')
            if orderItem.get('sku') and item.isCheckStock:
                # 校验sku库存
                sku = SkuDao().findOneByObjId(orderItem.get('sku'))
                if sku.stock < orderItem.get('payCount'):
                    return response_message('库存不足')
    elif data.get('scene') == 'guest':
        return False
    else:
        return False

# 创建订单
def createOrderScene(params, data, user):
    res = beforeCreateOrderScene(params, data, user)
    print('开始创建订单', res, params)
    if res:
        return res
    if data.get('scene') == 'generay' or data.get('scene') == 'goldCustom':
        data['content'] = json.dumps(params.get('orderItemList'))
        _order = OrderDao().create(data)
        # 创建订单成功之后，减少库存
        content = json.loads(_order.content)
        for item in content:
            if item.get('sku'):
                SkuDao().subStock(item.get('sku'), item.get('payCount'))
        return response_success({'orderId': _order.orderId})
    elif data.get('scene') == 'guest':
        data['content'] = json.dumps(params.get('orderItemList'))
        _order = OrderDao().create(data)
        return response_success({'orderId': _order.orderId})
    else:
        return response_message('支付场景不存在')
        
# 支付成功返回
def payReturnScene(payway, orderId):
    _order = OrderDao().findOneByOrderId(orderId)
    if _order.scene == 'generay' or _order.scene == 'goldCustom':
        if _order.orderStatus == 'WAIT_PAY':
            data = {}
            data['orderStatus'] = 'WAIT_SEND'
            data['payTime'] = datetime.now()
            data['payway'] = payway
            _order = OrderDao().update(_order.id, data)
            # 处理购买商品后销量库存等信息
            buyItemHandle(_order)
            # 处理活动信息
            if _order.activity:
                if _order.activity.key == 'goldCustom':
                    goldCustomHandle(_order)
                    updateVerticalPerformance('add', _order.user, _order.realPay) # 增加直推业绩
                    updateTeamPerformance('add', _order.user, _order.realPay)  # 增加团队业绩

    elif _order.scene == 'guest':
        if _order.orderStatus == 'WAIT_PAY':
            data = {}
            data['orderStatus'] = 'WAIT_SEND'
            data['payTime'] = datetime.now()
            data['payway'] = payway
            _order = OrderDao().update(_order.id, data)

# 取消订单返回
def cancelOrderReturnScene(orderId):
    order = OrderDao().findOneByOrderId(orderId)
    # 返还库存 和 扣除销量
    content = json.loads(order.content)
    if order.scene == 'generay' or order.scene == 'goldCustom':
        for item in content:
            if item.get('sku'):
                ItemDao().subSales(item.get('item'), item.get('payCount'))
                SkuDao().addStock(item.get('sku'), item.get('payCount'))
                SkuDao().subSales(item.get('sku'), item.get('payCount'))
    elif order.scene == 'guest':
        return